import React, { useState, useEffect, useRef } from 'react';
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col, Modal } from 'antd';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useModelAssociateMapping, useModelAssociateType } from '@/components';
import cmdbres from '@/data/cmdbres';
import hcpiam from '@/data/hcpiam';
import request, { requestIAM } from '@/utils/request';
import regexpUtil from '@/utils/regexpUtil';
import hcpUtils from '@/utils/hcpUtils';

const { uniqueIdentificationRegexp, commonNameRegexp } = regexpUtil;
const user = hcpUtils.getUser();
const CreateRelation = ({ history, moduleInfo, visible, setVisible, onCreateFinish }) => {
    const [loading, setLoading] = useState(false);
    const [mapping] = useModelAssociateMapping();
    const [{ associateTypeData }] = useModelAssociateType();
    const [targeteModelData, setTargeteModelData] = useState([]);
    const [selectTypeValues, setSelectTypeValues] = useState({});
    const [form] = Form.useForm();

    const queryKindModule = async () => {
        try {
            let res = await request({
                ...cmdbres.queryKindModule,
            });
            if (res && res.code == 200) {
                let data = res.data?.filter((item) => item.cmModuleId !== moduleInfo?.cmModuleId);
                setTargeteModelData(data);
            }
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        if (visible && moduleInfo) {
            changeType('srcModuleId', moduleInfo.cmModuleId, {
                srcModuleId: moduleInfo.cmModuleId,
                srcModuleCode: moduleInfo.moduleCode,
                srcModuleName: moduleInfo.moduleName,
            });
            queryKindModule();
        }
    }, [visible]);

    const onFinish = async (fieldsValue) => {
        setLoading(true);
        let param = {
            moduleAssociateCode: fieldsValue.moduleAssociateCode,
            moduleAssociateName: fieldsValue.moduleAssociateName,
            description: fieldsValue.description,
            namespace: 'default',
            author: user.staffName,
            associateTypeName: associateTypeData.find(
                ({ associateTypeCode }) => associateTypeCode === fieldsValue.associateType
            ).name,
            ...selectTypeValues,
        };
        let res = await request({
            ...cmdbres.createModelAssociate,
            data: param,
        });
        setLoading(false);
        if (res && res.code == 200) {
            setVisible(false);
            message.success('保存成功！');
            if (typeof onCreateFinish == 'function') onCreateFinish(res);
        }
    };

    const changeType = (type, value, option) => {
        let selectType = { ...selectTypeValues };
        if (option) {
            Object.assign(selectType, option);
        } else {
            selectType[type] = value;
        }
        setSelectTypeValues(selectType);

        if (selectType.destModuleCode && selectType.associateType) {
            form.setFieldsValue({
                moduleAssociateCode: `${selectType.srcModuleCode}_${selectType.associateType}_${selectType.destModuleCode}`,
            });
        }
    };

    const handleClose = () => {
        setVisible(false);
    };

    return (
        <Modal
            title="新建模型关联"
            className="hcp-modal-md"
            width={600}
            visible={visible}
            footer={null}
            onCancel={handleClose}
            destroyOnClose
            maskClosable={false}
            afterClose={() => {
                form.resetFields();
            }}
        >
            <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} name="basic" onFinish={onFinish}>
                <Form.Item
                    label="目标模型"
                    name="targeteModel"
                    key="targeteModel"
                    rules={[{ required: true, message: '请选择目标模型' }]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: '100%', marginRight: 10 }}
                        onChange={(value, option) => {
                            changeType('destModuleId', value, {
                                destModuleId: option.key,
                                destModuleCode: option.value,
                                destModuleName: option.name,
                            });
                        }}
                        showSearch
                    >
                        {targeteModelData?.map((item, index) => (
                            <Select.Option key={item.cmModuleId} value={item.moduleCode} name={item.moduleName}>
                                {item.moduleName}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item
                    label="关联类型"
                    name="associateType"
                    key="associateType"
                    rules={[{ required: true, message: '请选择关系类型' }]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: '100%', marginRight: 10 }}
                        onChange={(value) => changeType('associateType', value)}
                    >
                        {associateTypeData?.map((item, index) => (
                            <Select.Option
                                key={item.associateTypeCode}
                                value={item.associateTypeCode}
                                disabled={item.associateTypeCode == 'cm_mainline'}
                            >
                                {item.associateTypeCode}({item.name})
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="模型关联ID" name="moduleAssociateCode" required>
                    <Input placeholder="请输入模型关联ID" readOnly />
                </Form.Item>
                <Form.Item
                    label="模型关联名称"
                    name="moduleAssociateName"
                    rules={[{ required: true, message: '请输入模型关联名称' }, commonNameRegexp(1, 200)]}
                >
                    <Input placeholder="请输入模型关联名称" maxLength={200} />
                </Form.Item>
                <Form.Item
                    label="源-目标约束"
                    name="modelMapping"
                    key="modelMapping"
                    rules={[{ required: true, message: '请选择源-目标约束' }]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: '100%', marginRight: 10 }}
                        onChange={(value) => {
                            changeType('mapping', value);
                        }}
                    >
                        {mapping?.map((item, index) => (
                            <Select.Option key={index} value={item}>
                                {item}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="关联描述" name="description" key="description">
                    <Input.TextArea />
                </Form.Item>
                <div className="hcp-modal-body-footer">
                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button onClick={handleClose}>取消</Button>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            确认
                        </Button>
                    </Form.Item>
                </div>
            </Form>
        </Modal>
    );
};

export default CreateRelation;
